<!-- 全局统计 -->

<template>
  <view>
    <t-tabs v-model="activeTab">
      <t-tab-panel v-for="item in tabList" :value="item.value" :label="item.label">
        <template #panel>
          <div class="mainBox">
            <div class="headerBox">
              <t-card bordered :style="{ width: '190px' }">
                <div class="title">今日新增(人)</div>
                <div class="foot">{{ baseStats.todayNewCount }}</div>
              </t-card>
              <t-card bordered :style="{ width: '190px' }">
                <div class="title">总数(人)</div>
                <div class="foot">{{ baseStats.totalCount }}</div>
              </t-card>
            </div>
            <div v-for="(table, idx) in tableConfigs" :key="idx">
              <t-card bordered>
                <div class="foot">
                  <MyTable :bordered="true" :columns="table.columns" :headerBackgroundColor="'#f2f2f2'"
                    :headerColor="'#000'" :data="table.data.value" rowKey="orderNumber">
                  </MyTable>
                </div>
              </t-card>
            </div>
          </div>
        </template>
      </t-tab-panel>
    </t-tabs>
  </view>
</template>
<script setup lang="tsx">
import { ref, onMounted, watch } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import { List, } from '@/api/statistics/globalStatistics/globalStatistics';
import { getGradeList } from '@/api/member/level';


const baseStats = ref({ todayNewCount: 0, totalCount: 0 });

const tableConfigs = [
  {
    columns: [
      {
        title: '新注册会员做任务人数',
        colKey: 'todayNewMemberWithAnswer'
      },
      {
        title: '做任务总人数',
        colKey: 'totalAnswerUsers'
      },
      {
        title: '任务领取',
        colKey: 'totalAnswerRecords'
      },
      {
        title: '任务成功',
        colKey: 'successTasks'
      },
      {
        title: '任务失败',
        colKey: 'failedTasks'
      },
    ],
    data: ref([{}]),
    key: 'todayTaskStats',
  },
  {
    columns: [
      {
        title: '日期',
        colKey: 'orderNumber'
      },
      {
        title: '购买会员人数',
        colKey: 'purchaseMemberCount'
      },
      {
        title: '充值',
        colKey: 'rechargeAmount'
      },
      {
        title: '提现',
        colKey: 'withdrawAmount'
      },
      {
        title: '下级任务返点',
        colKey: 'subordinateTaskPoints'
      },
      {
        title: '活动',
        colKey: 'activityAmount'
      },
      {
        title: '购买会员',
        colKey: 'purchaseMember'
      },
      {
        title: '推广奖励',
        colKey: 'promotionReward'
      },
      {
        title: '任务佣金',
        colKey: 'taskCommission'
      },
      {
        title: '其他',
        colKey: 'otherAmount'
      },
    ],
    data: ref([{}]),
    key: 'multiStats',
  },
  {
    columns: [
      {
        title: '今日注册',
        colKey: 'todayNewMembers'
      },
      {
        title: '昨日注册',
        colKey: 'yesterdayNewMembers'
      },
      {
        title: '本月注册',
        colKey: 'thisMonthNewMembers'
      },
      {
        title: '总人数',
        colKey: 'totalMembers'
      },
      {
        title: '当前余额',
        colKey: 'totalBalance'
      },
      {
        title: '当前总资产',
        colKey: 'orderNumber'
      },
      {
        title: '当前在线人数',
        colKey: 'orderNumber'
      },
    ],
    data: ref([{}]),
    key: 'memberStats',
  },
];

const activeTab = ref('0');
const tabList = ref([
  { label: '总计', value: '0' },
]);

onMounted(async () => {
  // 获取等级列表
  const gradeListRes = await getGradeList({
    pageNum: 1,
    pageSize: 999,
    state: 1,
  });
  if (gradeListRes?.rows && Array.isArray(gradeListRes.rows)) {
    tabList.value = [
      { label: '总计', value: '0' },
      ...gradeListRes.rows.map((item) => ({
        label: item.name,
        value: item.grade,
      })),
    ];
  }
  await fetchData(activeTab.value);
});

const fetchData = async (tabValue: string) => {
  let params = {};
  if (tabValue !== '0') {
    params = { level: tabValue };
  }
  const res = await List(params);
  if (res?.code === 200) {
    baseStats.value = res.data?.baseStats || {};
    const formatAmount = (obj: any, keys: string[]) => {
      if (!obj) return obj;
      keys.forEach(key => {
        if (obj[key] !== undefined && obj[key] !== null && !isNaN(obj[key])) {
          obj[key] = Number(obj[key]).toFixed(2);
        }
      });
      return obj;
    };
    const amountKeys = [
      'rechargeAmount', 'withdrawAmount', 'subordinateTaskPoints',
      'activityAmount', 'promotionReward', 'taskCommission', 'otherAmount',
      'totalBalance'
    ];
    tableConfigs[0].data.value = [res.data?.todayTaskStats || {}];
    tableConfigs[1].data.value = [
      { orderNumber: '今日统计', ...formatAmount(res.data?.todayStats, amountKeys) },
      { orderNumber: '昨日统计', ...formatAmount(res.data?.yesterdayStats, amountKeys) },
      { orderNumber: '本周统计', ...formatAmount(res.data?.weekStats, amountKeys) },
      { orderNumber: '本月统计', ...formatAmount(res.data?.monthStats, amountKeys) },
    ];
    tableConfigs[2].data.value = [
      formatAmount(res.data?.memberStats, amountKeys)
    ];
  }
};

// 监听tab切换
watch(activeTab, (val) => {
  fetchData(val);
});
</script>

<style scoped lang="less">
.mainBox {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;

  .headerBox {
    display: flex;
    gap: 16px;
  }

  .title {
    padding: 0 16px 16px;
    border-bottom: 1px solid #ddd;
  }

  .foot {
    padding: 16px;
  }
}
</style>

<style lang="less">
.mainBox {
  .t-card__body {
    padding: 16px 0 0 !important;
  }
}
</style>
